package com.xy.novelmanagement.service.impl;

import com.xy.model.*;
import com.xy.novelmanagement.mapper.NovelAddMapper;
import com.xy.novelmanagement.service.INovelAddService;
import com.xy.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class NovelAddServiceImpl implements INovelAddService {
    @Autowired
    private NovelAddMapper novelAddMapper;

    @Override
    public List<Catalog> getCatalogsByName(String novelName) {
        List<Catalog> catalogList = null;
        try {
            catalogList = novelAddMapper.getNovelCatalogs(novelName);
        } catch (Exception e) {
            log.error("错误消息：{}", e.getMessage(), e);
        }
        return catalogList;
    }

    @Override
    public String addCatalogByFile(String catalogName, String novelName, String content) {
        String result = "";

        try {
            if (novelAddMapper.existNovel(novelName)) {
                //插入章节
                novelAddMapper.insertCatalogMsg(novelName, catalogName, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                //插入章节内容
                novelAddMapper.insertCatalogContent(novelName, catalogName, content);
            } else {
                result = "小说不存在！";
            }
        } catch (Exception e) {
            log.error("错误消息：{}", e.getMessage(), e);
            result = "插入异常！";
        }
        return result;
    }

    /*
     * 添加小说章节内容
     * */
    @Override
    public String addCatalog(String novelName, String catalogName, String content) {
        String res = "";
        try {
            if (novelAddMapper.existNovel(novelName)) {
                //插入章节
                novelAddMapper.insertCatalogMsg(novelName, catalogName, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                //插入章节内容
                novelAddMapper.insertCatalogContent(novelName, catalogName, content);
            } else {
                res = "小说不存在！";
            }
        } catch (Exception e) {
            log.error("错误消息：{}", e.getMessage(), e);
            res = "插入异常！";
        }
        return res;
    }

    /*
     * 添加小说
     * */
    @Override
    @Transactional
    public String saveNovel(String novelName, String author, String intro, String novelType, Map<String, List<String>> catalogs) {
        String msg = "添加小说成功!";
        //判定作者是否存在，不存在则新建作者
        try {
            if (novelAddMapper.checkAuthor(author) < 1) {
                Author auth = new Author();
                auth.setNickName(author);
                auth.setSex("男");
                auth.setPassword("123456");
                log.info("开始添加作者......");
                novelAddMapper.addAuthor(auth);
                log.info("作者添加成功！");
            }
            //判断小说是否存在存在则更新小说信息
            if (novelAddMapper.checkNovel(novelName) < 1) {
                Novel novel = new Novel();
                novel.setBookName(novelName);
                novel.setBookIntro(intro);
                novel.setBookAuthor(author);
                List<NovelType> types = new ArrayList<>();
                NovelType type = new NovelType();
                type.setNovelName(novelName);
                type.setType(novelType);
                types.add(type);

                novel.setBookState("连载");
                novel.setNovelStatus("连载");
                novel.setUpdateTime(new Date());
                log.info("开始添加小说......");
                novelAddMapper.addNovel(novel);
                log.info("小说添加成功！");
                log.info("开始添加小说类型......");
                novelAddMapper.addNovelType(types);
                log.info("小说类型添加成功！");
                log.info("开始添加作者作品......");
                novelAddMapper.addAuthorWork(novel.getBookName(), novel.getBookAuthor(), new SimpleDateFormat("yyyy-MM-dd HH:ss").format(new Date()));
                log.info("作者作品添加成功！");
            }
            //清空小说章节和章节内容并插入新的章节内容
            log.info("开始清空小说章节......");
            novelAddMapper.cleanCatalog(novelName);
            log.info("清空小说章节成功！");
            log.info("开始清空小说章节内容......");
            novelAddMapper.cleanCatalogContent(novelName);
            log.info("清空小说章节内容成功！");
            addCatalogs(novelName, catalogs.get("catalogs"), new SimpleDateFormat("yyyy-MM-dd HH:ss").format(new Date()), 0);
            addCatalogContents(novelName, catalogs.get("catalogs"), catalogs.get("catalogContent"));
        } catch (Exception e) {
            e.printStackTrace();
            msg = "添加失败！";
        }
        return msg;
    }

    @Override
    public void saveCatalogMsg(Catalog catalog) {
        try {
            List<Catalog> catalogList = new ArrayList<>();
            catalogList.add(catalog);
            novelAddMapper.addCatalogs(catalogList);
            log.info("添加章节《{}》成功", catalog.getNovelCatalog());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveCatalogContent(CatalogContent content) {
        Writer writer=null;
        try {
            List<CatalogContent> list = new ArrayList<>();
            CatalogContent ct = new CatalogContent();
            ct.setNovelName(content.getNovelName());
            ct.setCatalog(content.getCatalog());
            ct.setCatalogContent(content.getCatalogContent().substring(0, 50));
            list.add(ct);
            novelAddMapper.addCatalogContents(list);
            String dir = PropertiesUtil.getValue("txtDir", "") + content.getNovelName();
            if(!Files.exists(Paths.get(dir))){
                boolean mkdirs = new File(dir).mkdirs();
                log.info("文件目录不存在,创建文件夹结果:{}",mkdirs?"成功":"失败");
            }
            String filePath = dir + File.separator + content.getCatalog() + ".txt";
            File file = new File(filePath);
			if(!file.exists()){
                boolean newFile = file.createNewFile();
                log.info("新建章节TXT文件{}",newFile?"成功":"失败");
            }
			writer= new BufferedWriter(new FileWriter(file));
			writer.write(content.getCatalogContent());
			writer.flush();
            log.info("添加章节《{}》成功", content.getCatalog());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void saveNovel1(Novel novel) {
        try {
            if (!(novelAddMapper.checkAuthor(novel.getBookAuthor()) > 0)) {
                Author auth = new Author();
                auth.setNickName(novel.getBookAuthor());
                auth.setSex("男");
                auth.setPassword("123456");
                log.info("开始添加作者......");
                novelAddMapper.addAuthor(auth);
                log.info("作者添加成功！");
            }
            if (!(novelAddMapper.checkNovel(novel.getBookName()) > 0)) {
                novelAddMapper.addNovel(novel);
                int count = novelAddMapper.getBookStatus(novel.getBookName());
                if (count != 1) {
                    String novelStatus = novel.getNovelStatus();
                    if (StringUtils.isEmpty(novelStatus)) {
                        novelStatus = "连载";
                    }
                    novelAddMapper.addBookStatus(novel.getBookName(), novelStatus);
                }
            }
            log.info("添加小说《{}》成功", novel.getBookName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveNovelType(String bookName, String novelType) {
        try {
            List<NovelType> list = new ArrayList<>();
            list.add(new NovelType(bookName, novelType));
            novelAddMapper.addNovelType(list);
            log.info("添加小说《{}》类型成功", bookName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 批量插入小说章节内容
     * */
    public void addCatalogContents(String novelName, List<String> catalogList, List<String> catalogContentList) throws Exception {
        List<CatalogContent> list = new ArrayList<>();
        for (int i = 0; i < catalogList.size(); i++) {
            CatalogContent catalog = new CatalogContent(novelName, catalogList.get(i), catalogContentList.get(i));
            list.add(catalog);
        }

        log.info("开始批量插入小说章节内容......");
        novelAddMapper.addCatalogContents(list);
        log.info("批量插入小说章节内容 成功！");
    }

    /*
     * 批量插入小说章节
     * */
    public void addCatalogs(String novelName, List<String> catalogList, String updateTime, int vip) throws Exception {
        List<Catalog> list = new ArrayList<>();
        for (int i = 0; i < catalogList.size(); i++) {
            Catalog catalog = new Catalog();
            catalog.setNovelName(novelName);
            catalog.setNovelCatalog(catalogList.get(i));
            catalog.setUpdateTime(new Date());
            catalog.setVip(vip);
            list.add(catalog);
        }
        log.info("开始批量插入小说章节......");
        novelAddMapper.addCatalogs(list);
        log.info("批量插入小说章节成功！");
    }

    @Override
    public Novel getNovelByName(String bookName) {
        Novel novel = new Novel();
        novel.setBookName(bookName);
        novel = novelAddMapper.selectNovel(novel);
        return novel;
    }

    @Override
    public void updateWords(Integer bookWords, String bookName) {
        Novel novel = new Novel();
        novel.setBookName(bookName);
        novel.setBookWords(bookWords);
        novelAddMapper.updateWords(novel);
    }
}
